/* eslint-disable no-plusplus, function-paren-newline */
/**
 * Created by mar105 on 2017-11-14.
 */
import React, { Component } from 'react';
import { Layout, Spin, Modal, Form, Row, Col, Icon, Button, Input, Select, DatePicker, message } from 'antd';
import MergeTableEdit from './MergeTableEdit/MergeTableEdit.js';
import styles from '../../index.less';
import baseHigher from './baseHigher';
import * as config from '../../utils/config';
import * as commonFunc from './commonFunc';
import PpopupPan from '../../routes/ppopupPan/secondPpopupPan';

const FormItem = Form.Item;
const { Option } = Select;
let uuid = 0;

class CommonClassify extends Component {
  constructor(props) {
    super(props);
    this.state = {
      btnData: config.btnData, /* 工具栏按钮 */
      masterConfig: { sId: '' }, // 主表 + 从表 配置
      masterData: [],
      selectedRowKeys: [],
      sActiveId: '',
      loading: false,
      modalVisible: false, /* 弹窗显示状态 */
      modalPanel: {}, /* 弹窗面板属性 */
      listRecordKey: '', /* 编辑行 */
      resultValue: {}, /* 通用列表弹窗返回数据 */
      data: [], /* 数据 */
      cudClose: false, /* 控制新增按钮是否显示开关 */
      firstColumns: [], /* 搜索字段 */
      expand: false, /* 快捷过滤显示与否 */
      dateFormat: commonFunc.getDateFormat(props.app.systemData),
    };
    this.seaJudge = config.seaJudge; /* 判断条件 */
  }

  componentWillMount() {
    if (this.props.app.ppopupPane !== undefined && this.props.app.ppopupPane.cudClose !== undefined) {
      this.setState({ cudClose: true });
    }
  }

  componentWillReceiveProps(nextProps) {
    const { systemData } = nextProps.app;
    const dateFormat = commonFunc.getDateFormat(systemData);
    this.setState({ dateFormat });
    const { dataList } = nextProps.content;
    const {
      sDataListTabId, formRoute, loading, urlData, returnType,
    } = dataList;
    /* 弹出窗数据返回,渲染数据并关闭弹出框 */
    /* 判断中加入了modalVisible状态,二级弹窗回带必然该状态是true，非二级弹窗则为false,避免在回带时候非二级弹窗面板也进入此方法 */
    if ((nextProps.app.secondppopupPane !== undefined && Object.keys(nextProps.app.secondppopupPane).length > 0) ? (nextProps.sTabId === nextProps.app.secondppopupPane.key
        && nextProps.formRoute === nextProps.app.secondppopupPane.route && this.state.modalVisible) : false) {
      const { resultValue, modalType } = nextProps.app.secondppopupPane;
      /* 通用弹窗数据返值处理 */
      if ((resultValue !== undefined) && modalType === 'ppopup') {
        const { data } = this.state;
        data.map((item) => {
          if ((item.sId === undefined ? item.key : item.sId) === this.state.listRecordKey) {
            for (const key of Object.keys(resultValue)) {
              item[`${key}`] = resultValue[`${key}`];
            }
          }
          return item;
        });
        /* 置空models中弹窗面板 */
        this.props.removeSecondModalPane({});
        /* 隐藏弹窗面板 */
        this.setState({ modalVisible: false, data });
      }
    }
    if ((nextProps.sTabId === sDataListTabId &&
      nextProps.formRoute === formRoute) || (nextProps.app.ppopupPane !== undefined && nextProps.sTabId === nextProps.app.ppopupPane.key && nextProps.formRoute === nextProps.app.ppopupPane.route) || (nextProps.app.secondppopupPane !== undefined && nextProps.sTabId === nextProps.app.secondppopupPane.key && nextProps.formRoute === nextProps.app.secondppopupPane.route)) {
      if (loading) {
        this.setState({ loading: true });
        return;
      } else if (loading !== undefined) {
        this.setState({ loading });
      }
      if (urlData !== undefined && urlData.formData !== undefined && this.state.masterConfig.sId === '') {
        const sActiveId = this.state.masterConfig.sId;
        const masterConfig = commonFunc.getTableConfig('Classify', urlData.formData);
        const { gdsconfigformslave } = masterConfig;
        const firstColumns = commonFunc.getFastConfig(gdsconfigformslave);
        this.setState({ masterConfig, sActiveId, firstColumns });
      }
      /* 通用分类的数据由外部保存并传入内部，用于回带可改变列表内容, 且只有面板状态modalVisible为false时才会进入 */
      if (returnType === 'isGetData' && !this.state.modalVisible) {
        /* 整合列表数据 */
        const data = [];
        dataList.urlData.map((child) => {
          const value = {
            key: child.sId !== undefined ? child.sSlaveId : child.key,
            handleType: child.handleType,
          };
          /* 双击回带时候存在回带隐藏值，所以表格中数据跟后台返回的数据走而不跟配置走 */
          /* TODO:此处存在风险点为:如果后台数据没值,则不进行该字段返回,待后续处理 */
          for (const item of Object.keys(child)) {
            if (item !== 'key') {
              value[item] = child[item];
            }
          }
          data.push(value);
          return '';
        });
        this.setState({
          data,
        });
      }
    }
  }

  shouldComponentUpdate(nextProps) {
    if (nextProps.app.ppopupPane !== undefined && nextProps.sTabId === nextProps.app.ppopupPane.key) {
      return true;
    }
    if (nextProps.sTabId === nextProps.app.currentPane.key) {
      return true;
    }
    return true;
  }

  /* 表格选择行ID-目前只支持一个表格 */
  handleSelectedRowKeys = (selectedRowKeys) => {
    this.setState({ selectedRowKeys });
  };

  /* 弹出框回带 */
  handleGetResult = (reslultValue) => {
    this.props.handleGetResult(reslultValue);
  };

  /* 弹出框回带自身 */
  handleGetSelfResult = (resultValue) => {
    this.props.handleGetSelfResult(resultValue);
  };

  /* 弹窗面板状态更改 */
  handleModalPane = (value) => {
    this.setState({ modalVisible: value.modalVisible });
  };

  /* 用于返回列表编辑框弹窗所属行主键 */
  handleRecordKey = (value) => {
    this.setState({ listRecordKey: value });
  };

  /* 新增数据添加 */
  handleSelfRecordAdd = (value) => {
    const { data } = this.state;
    /* 判断如果当前页跟每页多少条相等，则添加时删除最后一条（避免新增时超出当前页的条数，新增的那条则不出现） */
    if (data.length === config.pageSize) {
      data.splice(config.pageSize - 1, 1);
    }
    this.setState({ data: [value, ...data] });
  };

  /* 弹窗关闭 */
  handlePpopUpPaneCancel = () => {
    /* 隐藏弹窗面板 */
    this.setState({ modalVisible: false, listRecordKey: '' });
    /* 置空models中弹窗面板 */
    this.props.removeSecondModalPane({});
  };

  handleFields = (firstColumns, form) => {
    /* 默认快捷过滤 */
    const { dateFormat } = this.state;
    const count = this.state.expand ? 10 : 1;
    this.form = form;
    const { getFieldDecorator, getFieldValue } = form;
    getFieldDecorator('keys', { initialValue: [0] });
    const keys = getFieldValue('keys'); /* 代表一行下拉框的唯一键 */
    const children = keys.map((k) => {
      /* 字段列表 */
      const firstKey = getFieldValue(`first-${k}`) || firstColumns[0].key; /* 默认搜索字段 */
      const firstColType = firstKey.substring(0, 1); /* 搜索字段类型 */
      const columnOptions = firstColumns.map(child =>
        <Option key={child.key}>{child.value}</Option>);
      const secondCon = this.seaJudge[firstColType]; /* 搜索条件 */
      const conOptions = secondCon.map(child => <Option key={child.key}>{child.value}</Option>);
      const conKey = getFieldValue(`second-${k}`) || secondCon[0].key; /* 默认搜索条件值 */
      const secondKey = getFieldValue(`second-${k}`) || secondCon[0].key;
      const timeFlag = secondKey === 'day' || secondKey === 'month' || secondKey === 'week';
      const thirdRules = {
        initialValue: firstColType === 'b' ? '1' : firstColType === 't' ? null : '',
        rules: [{ required: !timeFlag, message: '请选择或输入内容!' }],
      };
      return (
        <Col span={24} key={k} style={{ display: k < count ? 'block' : 'none' }}>
          <Col span={8}>
            <FormItem className={styles.advFormItem}>
              {
                getFieldDecorator(`first-${k}`, {
                  initialValue: `${firstKey}`,
                })(
                  <Select
                    onChange={value => this.handleFirstChange(value, `second-${k}`)}
                  >
                    {columnOptions}
                  </Select>)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem className={styles.advFormItem}>
              {
                getFieldDecorator(`second-${k}`, {
                  initialValue: `${conKey}`,
                })(
                  <Select
                    onChange={value => this.handleSecondChange(value, `third-${k}-${firstColType}`)}
                  >
                    {conOptions}
                  </Select>)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem className={styles.advFormItem}>
              {
                getFieldDecorator(`third-${k}-${firstColType}`, thirdRules)(firstColType === 'b' ?
                  <Select className={styles.advInput}>
                    <Option value="1">是</Option>
                    <Option value="0">否</Option>
                  </Select>
                    : firstColType === 't' ?
                      <DatePicker
                        format={dateFormat}
                        className={styles.advInput}
                        disabled={timeFlag}
                      />
                    :
                      <Input placeholder="请输入你要搜索的内容" className={styles.advInput} />)
              }
              {k > 0 ? (
                <div className={styles.advDelectIcon}>
                  <Icon
                    type="minus-circle-o"
                    onClick={() => this.handleRemove(k)}
                  />
                </div>
              ) : null}
            </FormItem>
          </Col>
        </Col>
      );
    });
    return children;
  };

  handeToggle = () => {
    /* 是否展开多出的条件内容 */
    const { expand } = this.state;
    this.setState({ expand: !expand });
  };

  handleAdd = () => {
    /* 添加条件 */
    uuid++;
    const { form } = this;
    const keys = form.getFieldValue('keys');
    if (keys.length === 10) {
      const { gdsformconst } = this.props;
      const maxFilter = gdsformconst.filter(item => (item.sName === 'maxFilter'))[0].showName;
      return message.warning(maxFilter);
    } else {
      const nextKeys = keys.concat(uuid);
      form.setFieldsValue({
        keys: nextKeys,
      });
    }
  };


  handleFirstChange = (value, secondValue) => {
    /* 第二控件更改，再第一控件更改的情况，第二控件默认值设置 */
    const firstColType = value.substring(0, 1);
    const secondCon = this.seaJudge[firstColType];
    const { setFieldsValue } = this.form;
    setFieldsValue({
      [secondValue]: secondCon[0].key,
    });
  };

  handleRemove = (k) => {
    /* 移除添加条件 */
    const { form } = this;
    const keys = form.getFieldValue('keys');
    if (keys.length === 1) {
      return;
    }
    form.setFieldsValue({
      keys: keys.filter(key => key !== k),
    });
  };

  handleReset = () => {
    /* 清空搜索条件 */
    uuid = 0;
    this.form.resetFields();
    const { firstColumns } = this.state;
    const firstKey = firstColumns[0].key;
    const firstColType = firstKey.substring(0, 1);
    const secondCon = this.seaJudge[firstColType]; /* 搜索条件 */
    const { setFieldsValue } = this.form;
    setFieldsValue({
      'first-0': firstKey,
      'second-0': secondCon[0].key,
    });
    this.setState({ expand: false });
    // this.props.onSaveFilter([]);
  };

  render() {
    const { loading } = this.state;
    const { pageLoading } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
    const { firstColumns } = this.state;
    return (
      <Spin spinning={loading}>
        {pageLoading ? '' :
        <Layout className={styles.clayoutClassify}>
          <Layout className={styles.clayoutTop}>
            {
              firstColumns.length > 0 ?
                <AdvancedSearchForm
                  {...this.state}
                  handleSearch={this.handleSearch}
                  handleFields={this.handleFields}
                  handeToggle={this.handeToggle}
                  handleAdd={this.handleAdd}
                  handleReset={this.handleReset}
                  formItemLayout={formItemLayout}
                />
                : ''
            }
            <MergeTableEdit
              {...this.props}
              {...this.state}
              componentName="CommonClassify"
              onSelectedRowKeys={this.handleSelectedRowKeys.bind(this)}
              config={this.state.masterConfig}
              handleGetResult={this.handleGetResult.bind(this)}
              handleGetSelfResult={this.handleGetSelfResult.bind(this)}
              handleModalPane={this.handleModalPane.bind(this)}
              handleRecordKey={this.handleRecordKey.bind(this)}
              handleSelfRecordAdd={this.handleSelfRecordAdd.bind(this)}
              handleSelf
            />
            <Modal
              title={Object.keys(this.state.modalPanel).length > 0 ? this.state.modalPanel.title : ''}
              visible={this.state.modalVisible}
              onCancel={this.handlePpopUpPaneCancel.bind(this)}
              footer={null}
              width={1000}
              zIndex={1000}
              wrapClassName={styles.modal}
            >
              <PpopupPan />
            </Modal>
          </Layout>
        </Layout>
        }
      </Spin>
    );
  }
}

const AdvancedSearchForm = Form.create()((props) => {
  const {
    handleSearch, handleFields,
    handeToggle, handleAdd, handleReset,
  } = props;
  const { firstColumns, form, expand } = props;
  return (
    <Form
      className={styles.advForm}
      onSubmit={handleSearch}
    >
      <Row className={expand ? styles.advRowActive : styles.advRow}>
        {handleFields(firstColumns, form)}
        <button onClick={handeToggle}>
          <Icon type={expand ? 'up' : 'down'} />
        </button>
        <Col span={24} style={{ display: expand ? 'block' : 'none' }}>
          <div className={styles.advButton}>
            <Button
              type="primary"
              onClick={handleAdd}
            >
              <Icon type="plus" /> 添加条件
            </Button>
          </div>
        </Col>
      </Row>
      <Col span={24} className={styles.advCol}>
        <Button type="primary" htmlType="submit">搜索</Button>
        <Button type="primary" style={{ marginLeft: 8 }} onClick={handleReset}>
            清空
        </Button>
      </Col>
    </Form>
  );
});


export default baseHigher(CommonClassify);
